package com.usian.wemedia.gateway.filter;


import com.usian.wemedia.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        if (request.getPath().value().contains("/login/in")) {
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        List<String> token = headers.get("token");
        if (token == null || token.size() == 0 || StringUtils.isBlank(token.get(0))) {
            String json = "{\"errorMsg\":\"dont have token\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        try {
            String s = token.get(0);
            //eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWLQQqEMAwA_5Kzhaba2vibqhEqKIW0oMj-fePB2wzDPLDXDBMgBWZEZ-ZI1gyrZ0NxRBMWosHZjZaNoIOcKkwYvLd977zrQNqst9xS-Xi7iGqTnE611Fa1VIoyX-U7Q3zPrA0R6fcHYJLsjYMAAAA.snFuOPQEkvSoG7GX8qf8DVZgTEBWBZyQufAJM7d22TMbQwKMGMrtw4Zyf1O26-uS4tJox9D_v1VCwE5LtZrnzQ
            Claims claims = AppJwtUtil.getClaimsBody(s);
            int i = AppJwtUtil.verifyToken(claims);
            if (i == 0 || i == -1) {
                //5.1 合法，则向header中重新设置userId
                Integer id = (Integer) claims.get("id");
                //重新设置token到header中
                ServerHttpRequest serverHttpRequest1 = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id + "");
                }).build();
                exchange.mutate().request(serverHttpRequest1).build();
            }

        } catch (Exception e) {

            String json = "{\"errorMsg\":\"s is invalid\"}";
            return response.writeWith(Flux.just(response.bufferFactory().wrap(json.getBytes())));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
